package com.genius.exception;

import com.genius.core.JSONResult;
import com.genius.enums.ResponseType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Objects;

/**
 * 精简返回给客户端的异常内容
 */
@Slf4j
@RestControllerAdvice
public class ExceptionAdvice {

    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(Exception.class)  //捕获Exception类型异常
    public JSONResult exceptionHandler(Exception e){
        log.error("执行异常",e);
        //后端验证抛出的异常
        if(e instanceof MethodArgumentNotValidException){
            MethodArgumentNotValidException exception = (MethodArgumentNotValidException) e;
            return JSONResult.errorMsg(Objects.requireNonNull(exception.getBindingResult().getFieldError()).getDefaultMessage());
        }else if(e instanceof IotException){
            IotException exception = (IotException) e;
            return JSONResult.errorCustom(exception.getResponseType());
        }else if(e instanceof RuntimeException){
            RuntimeException exception = (RuntimeException) e;
            return JSONResult.errorMsg(exception.getMessage());
        }else{
            return JSONResult.errorCustom( ResponseType.FAILED);
        }
    }
}